<?php


namespace App\Extensions\Exporters;


use App\PatentApply;
use Carbon\Carbon;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Concerns\WithMapping;

class PatentApplyExporter extends ExcelExporter implements WithMapping
{
    protected $fileName = '专利申请列表.xlsx';
    protected $role = 0;

    protected $columns = [
        'uuid' => '登记编号',
        'patent_name' => '专利名称',
        'patent_sn' => '申请号',
        'apply_date' => '申请日',
        'publication_num' => '公告号',
        'publication_date' => '公告日',
        'patent_type_id' => '专利类型',
        'patent_person' => '第一申请人',
        'other_applicant' => '合作单位',
        'charge_person' => '专利负责人/第一发明人',
        'inventor' => '全体发明人',
        'department_id' => '所属科室',
        'contact_person' => '联系人',
        'phone' => '联系电话',
        'country' => '国家',
        'apply_channel' => '申请途径',
        'other_patent_sn' => '其他申请号',
        'agency_id' => '意向代理机构',
        'retrieval_remark' => '检索结论',
        'id' => '评估意见',
        'score' => '评分',
        'funding'=>'经费资助',
        'created_at' => '创建时间'
    ];

    public function __construct(Grid $grid = null)
    {
        parent::__construct($grid);
    }

    public function map($row): array
    {
        return [
            $row->uuid,
            $row->patent_name,
            $row->patent_sn . "\t",
            $row->apply_date,
            $row->publication_num . "\t",
            $row->publication_date,
            data_get(patent_type_select_option(), $row->patent_type_id, ''),
            $row->patent_person,
            $row->other_applicant,
            $row->charge_person,
            $row->inventor,
            $row->department->name ?? '',
            $row->contact_person,
            $row->phone . "\t",
            $row->country,
            data_get(PatentApply::APPLY_CHANNEL, $row->apply_channel, ''),
            $row->other_patent_sn,
            $row->agency->name ?? '',
            $row->retrieval_remark,
            $this->pg($row),
            $row->score,
            $row->funding,
            Carbon::parse($row->created_at)->toDateString(),
        ];
    }

    public function setFileName($name)
    {
        $this->fileName = $name . '.xlsx';
        return $this;
    }

    protected function pg($row)
    {
        if ($this->role == 1) {
            return $row->assesses->where('state', 1)->values()->map(function ($item) {
                return sprintf('%s：', $item->expert->name ?? '');
            })->implode("\n");
        }
        return $row->assesses->where('state', 1)->values()->map(function ($item, $key) {
            return sprintf('专家%s：', $key + 1);
        })->implode("\n");
    }

    public function setRoleType($role): self
    {
        $this->role = $role;
        return $this;
    }


}
